define(function (require) {
    "use strict";
    var ko = require("knockout");
    var komapping = require("komapping");
    var router = require("plugins/router");
    var layui = require("layui");
    var $ = require("jquery");
    var system = require("durandal/system");

    var TreeNodeStaeTemp = function () {
        var self = this;

        self.treeNodeIsOpenTemp = {};
        self.currentTId = null;

        self.saveIsOption = function (treeNode) {
            if ((typeof treeNode === "object") && (treeNode != null)) {
                var open = (treeNode.open === true) ? true : false;
                treeNode.open = open;
                self.treeNodeIsOpenTemp[treeNode.id.toString()] = open;
                return open;
            }
        };
        self.resetFromTemp = function (data) {
            var tempIsOpen = (self.treeNodeIsOpenTemp[data.id.toString()] === true) ? true : false;
            data.open = tempIsOpen;
            for (var i = 0; i < data.children.length; i++) {
                treeNodeStaeTemp.resetFromTemp(data.children[i]);
            }
            return data;
        };

        self.saveCurrent = function (treeNode) {
            self.currentTId = treeNode.tId;
        };
        self.selectTempNode = function () {
            var treeObj = $.fn.zTree.getZTreeObj("tree-list");
            if (self.currentTId !== null) {
                var currentNode = treeObj.getNodeByTId(self.currentTId);
                if (currentNode !== null) {
                    treeObj.selectNode(currentNode);
                }
            }
        };
        /*self.findItemById = function (id, currentNodes) {
            for (var i = 0; i < currentNodes.length; i++) {
                var node = currentNodes[i];
                if (node.id === id) {
                    return node;
                }
                var childrenResult = self.findItemById(id, node.children);
                if (childrenResult !== null) {
                    return childrenResult;
                }
            }
            return null;
        };*/
    };

    var treeNodeStaeTemp = new TreeNodeStaeTemp();

    var nodeModel = ko.observable(null);
    var testNews = ko.observableArray([]);

    return {
        nodeModel: nodeModel,
        testNews: testNews,
        compositionComplete: function () {
            layui.use(["element", "form", "layer", "table"], function () {
                var layer = layui.layer;
                var element = layui.element;
                var table = layui.table;
                var form = layui.form;
                element.render();
                form.render();

                var addHoverDom = function (treeId, treeNode) {
                    var sObj = $("#" + treeNode.tId + "_span");
                    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
                    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
                        + "' title='add node' onfocus='this.blur();'></span>";
                    sObj.after(addStr);
                    var btn = $("#addBtn_" + treeNode.tId);
                    if (btn) btn.click(function () {
                        $.ajax({
                            type: "post",
                            url: "/back/addSubNode/" + treeNode.id,
                            dataType: "json"
                        }).then(function (response) {
                            if (response.data === true) {
                                refreshTree();
                            }
                        }, function (data) {
                            layer.alert(data.responseJSON.msg);
                        });
                    });
                };

                var removeHoverDom = function (treeId, treeNode) {
                    $("#addBtn_" + treeNode.tId).unbind().remove();
                };

                var showRemoveBtn = function (treeId, treeNode) {
                    return true;
                };

                var showRenameBtn = function (treeId, treeNode) {
                    return true;
                };

                var beforeEditName = function (treeId, treeNode) {
                    var zTree = $.fn.zTree.getZTreeObj("tree-list");
                    zTree.selectNode(treeNode);
                    setTimeout(function () {
                        zTree.editName(treeNode);
                    }, 0);
                    return false;
                };

                var beforeRemove = function (treeId, treeNode) {
                    var zTree = $.fn.zTree.getZTreeObj("tree-list");
                    zTree.selectNode(treeNode);
                    layui.use(["layer"], function () {
                        var layer = layui.layer;
                        layer.confirm("是否删除此节点？", {
                            btn: ["删除", "取消"] //按钮
                        }, function (index, layero) {
                            layer.close(index);
                            $.ajax({
                                type: "delete",
                                url: "/back/node/" + encodeURIComponent(treeNode.id),
                                dataType: "json"
                            }).then(function (response) {
                                if (response.data === true) {
                                    refreshTree();
                                }
                            }, function (data) {
                                layui.use(["layer"], function () {
                                    var layer = layui.layer;
                                    layer.alert(data.responseJSON.msg);
                                });
                            });
                        }, function (index) {
                            layer.close(index);
                        });
                    });
                    return false;
                };

                var onRemove = function (e, treeId, treeNode) {
                };

                var zTreeOnExpand = function (event, treeId, treeNode) {
                    treeNodeStaeTemp.saveIsOption(treeNode);
                };

                var zTreeOnCollapse = function (event, treeId, treeNode) {
                    treeNodeStaeTemp.saveIsOption(treeNode);
                };

                var beforeRename = function (treeId, treeNode, newName, isCancel) {
                    var cancleEdit = function () {
                        setTimeout(function () {
                            var zTree = $.fn.zTree.getZTreeObj("tree-list");
                            zTree.cancelEditName();
                            alert("节点名称不能为空.");
                        }, 0);
                        return false;
                    };
                    var executeEdit = function () {
                        $.ajax({
                            type: "put",
                            url: "/back/node/" + encodeURIComponent(treeNode.id) + "?name=" + encodeURIComponent(newName),
                            dataType: "json"
                        }).then(function (response) {
                            if (response.data === true) {
                                refreshTree();
                                updateNodeInfoByTreeId(treeNode.id);
                            }
                        }, function (data) {
                            layui.use(["layer"], function () {
                                var layer = layui.layer;
                                layer.alert(data.responseJSON.msg);
                            });
                        });
                        return true;
                    };
                    return ((newName.length == 0) ? cancleEdit() : executeEdit());
                };

                function onRename(e, treeId, treeNode, isCancel) {
                    //console.log(treeNode);
                };

                function updateNodeInfoByTreeId(treeIdObj) {
                    var treeId = parseInt(treeIdObj);
                    if ((typeof treeId === "number") && (treeId > 0)) {
                        $.ajax({
                            type: "get",
                            url: "/back/nodeInfo/" + encodeURIComponent(treeId),
                            dataType: "json"
                        }).then(function (response) {
                            nodeModel(komapping.fromJS(response.data));
                            form.render();
                        }, function (data) {
                            layer.alert(data.responseJSON.msg);
                        });
                    } else {
                        nodeModel(null);
                        form.render();
                    }
                };

                var zTreeOnClick = function (event, treeId, treeNode) {
                    if ((typeof treeNode === "object") && (treeNode !== null)) {
                        treeNodeStaeTemp.saveCurrent(treeNode);
                        updateNodeInfoByTreeId(treeNode.id);
                    } else {
                        updateNodeInfoByTreeId(null);
                    }
                };

                var zTreeBeforeDrop = function (treeId, treeNodes, targetNode, moveType) {
                    //console.log(treeNodes);
                    //console.log(targetNode);
                    var source = (typeof treeNodes[0] === "object") ? treeNodes[0] : null;
                    var parentNode = (typeof targetNode === "object") ? targetNode : null;
                    if ((source !== null) && (parentNode !== null)) {
                        $.ajax({
                            type: "put",
                            url: "/back/moveNode?sourceId=" + encodeURIComponent(source.id) + "&parentId=" + encodeURIComponent(parentNode.id),
                            dataType: "json"
                        }).then(function (response) {
                            refreshTree();
                        }, function (data) {
                            layer.alert(data.responseJSON.msg);
                        });
                    }
                    return false;
                };

                var setting = {
                    view: {
                        addHoverDom: addHoverDom,
                        removeHoverDom: removeHoverDom,
                        selectedMulti: false
                    },
                    edit: {
                        enable: true,
                        editNameSelectAll: true,
                        drag: {
                            prev: false,
                            inner: true,
                            next: false,
                            isCopy: false,
                            isMove: true
                        },
                        showRemoveBtn: showRemoveBtn,
                        showRenameBtn: showRenameBtn
                    },
                    callback: {
                        beforeEditName: beforeEditName,
                        beforeRemove: beforeRemove,
                        beforeRename: beforeRename,
                        onRemove: onRemove,
                        onRename: onRename,
                        onExpand: zTreeOnExpand,
                        onCollapse: zTreeOnCollapse,
                        onClick: zTreeOnClick,
                        beforeDrop: zTreeBeforeDrop
                    },
                    data: {
                        simpleData: {
                            enable: false
                        }
                    }
                };

                var refreshTree = function () {
                    return $.ajax({
                        type: "get",
                        url: "/back/nodes",
                        dataType: "json"
                    }).then(function (response) {
                        $(function () {
                            $.fn.zTree.init($("#tree-list"), setting, treeNodeStaeTemp.resetFromTemp(response.data));
                            treeNodeStaeTemp.selectTempNode();
                        });
                    }, function (data) {
                        layer.alert(data.responseJSON.msg);
                    });
                };

                refreshTree();

                form.on("submit(selector-test-case)", function (data) {
                    layer.open({
                        content: "正在请求数据...",
                        shadeClose: true,
                        closeBtn: 0,
                        btn: [],
                        success: function (layero, index) {
                            $.ajax({
                                type: "get",
                                url: "/back/selectorTestCase?url=" + encodeURIComponent(data.field.url)
                                + "&timeSelector=" + encodeURIComponent(data.field.timeSelector)
                                + "&titleSelector=" + encodeURIComponent(data.field.titleSelector)
                                + "&timeFormatter=" + encodeURIComponent(data.field.timeFormatter),
                                dataType: "json"
                            }).then(function (response) {
                                layer.close(index);
                                testNews(response.data);
                                layer.open({
                                    type: 1,
                                    area: "600px",
                                    shadeClose: true,
                                    success: function (layero, index) {
                                    },
                                    content: $("#selector-test-result").html()
                                });
                            }, function (data) {
                                layer.close(index);
                                layer.alert(data.responseJSON.msg);
                            });
                        }
                    });

                    return false;
                });

                form.on("submit(create-plan)", function (data) {
                    $.ajax({
                        url: "/back/nodeInfo",
                        type: "post",
                        dataType: "json",
                        contentType: "application/json",
                        data: JSON.stringify(data.field)
                    }).then(function (response) {
                        layer.alert(response.msg);
                        updateNodeInfoByTreeId(data.field.treeNodeId);
                    }, function (data) {
                        layer.alert(data.responseJSON.msg);
                    });
                    return false;
                });

                form.on("submit(update-plan)", function (data) {
                    $.ajax({
                        url: "/back/nodeInfo",
                        type: "put",
                        dataType: "json",
                        contentType: "application/json",
                        data: JSON.stringify(data.field)
                    }).then(function (response) {
                        layer.alert(response.msg);
                        updateNodeInfoByTreeId(data.field.treeNodeId);
                    }, function (data) {
                        layer.alert(data.responseJSON.msg);
                    });
                    return false;
                });
            });
        }
    };
});